import Vue from 'vue'
import VueRouter from 'vue-router'
const NotFound = () => import('../views/page404/page404.vue')
const Login = () => import('../views/login/login.vue')
const index = () => import('../views/layout/index.vue')
const homepage = () => import('../views/homepage/homepage.vue')
const article = () => import('../views/articles/article.vue')
const image = () => import('../views/images/image.vue')
const edit = () => import('../views/articles/edit.vue')
const add = () => import('../views/articles/add.vue')
const comment = () => import('../views/comment/comment.vue')
const fans = () => import('../views/fans/fans.vue')
const settings = () => import('../views/settings/settings.vue')
Vue.use(VueRouter)

const routes = [
  {
    path: '/', // 直接跳转到登录页面
    redirect: '/login'
  },
  {
    path: '/login', // 配置路由
    component: Login
  },
  {
    path: '/index',
    component: index,
    children: [
      {
        path: '/',
        component: homepage,
        meta: {
          title: '首页'
        }
      },
      {
        path: '/articles',
        component: article,
        meta: {
          title: '内容管理'
        }
      },
      {
        path: '/image',
        component: image,
        meta: {
          title: '素材管理'
        }
      },
      {
        path: '/edit:id',
        component: edit,
        meta: {
          title: '发布文章'
        }
      },
      {
        path: '/addArticle',
        component: add,
        meta: {
          title: '添加文章'
        }
      },
      {
        path: '/comment',
        component: comment,
        meta: {
          title: '评论管理'
        }
      },
      {
        path: '/fans',
        component: fans,
        meta: {
          title: '粉丝管理'
        }
      },
      {
        path: '/settings',
        component: settings,
        meta: {
          title: '个人设置'
        }
      }
    ]
  },
  { path: '*', component: NotFound }
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  console.log(Date.now(), '路由跳转了')
  console.log(to, from, next)
  // 如果你要去的页面是 "VIP" 页面
  const pageList = ['/index', '/image', '/articles', '/addArticle']
  // if (to.path === '/image' || to.path === '/article') {
  if (pageList.includes(to.path)) {
    // 1. 获取token
    const token = localStorage.getItem('token')
    if (token) {
      next() // 如果带有token放行
    } else {
      next('/login')
    }
  } else {
    next() // 放行
  }
  if (to.meta.title) {
    document.title = 'HMPC | ' + to.meta.title
  } else {
    document.title = 'HMPC'
  }
})

export default router
